# -*- coding: utf-8 -*-
import requests
from django.views import View

__author__ = 'JK'
__date__ = '2019/4/11 22:55'

import json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from utils.responses import CommonResponseMixin, ReturnCode

# Create your views here.

# from thirdparty import weather


# def weatherview(request):
#     if request.method == 'GET':
#         cityid = request.GET.get('cityid')
#         data = weather.weatherapi(cityid)
#         print(data)
#         return JsonResponse(data=data, json_dumps_params={'ensure_ascii':False})
#         # return HttpResponse(content=data, status=200)
#     elif request.method == 'POST':
#         received_body = request.body
#         received_body = json.loads(received_body)
#         cities = received_body.get('cities')
#         response_data = []
#         for city in cities:
#             result = weather.weatherapi(city)
#             response_data.append(result)
#         return JsonResponse(data=response_data, safe=False, json_dumps_params={'ensure_ascii':False})




def weatherapi(city):
    url = 'https://www.apiopen.top/weatherApi'
    data = {"city": city}
    r = requests.post(url=url, data=data)
    # print(r.text)
    x = json.loads(r.text)
    return  x['data']['forecast'][0]


class weatherview(View, CommonResponseMixin):
    def get(self, request):
        city = request.GET.get('city')
        data = weatherapi(city)
        response = []
        response.append(data)
        response = self.wrap_json_response(data=response, code=ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False)

    def post(self, request):
        received_body = request.body
        received_body = json.loads(received_body)
        cities = received_body.get('cities')
        response_data = []
        for city in cities:
            result = weatherapi(city)
            result['city'] = city
            response_data.append(result)
        response = self.wrap_json_response(data=response_data, code=ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False)

